package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.BookVersionDao;
import jumpingnotes.model.entity.BookVersion;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class BookVersionHibernateDao extends GenericHibernateDao<BookVersion> implements BookVersionDao
{
	public BookVersionHibernateDao()
	{
		super(BookVersion.class);
	}

	@SuppressWarnings("unchecked")
	public List<BookVersion> findValueByBookIdAndProperty(final int bookId, final String property)
	{
		return (List<BookVersion>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select bv from BookVersion bv where bv.book.bookId=:bookId and bv.property=:property order by bv.weight desc");
				query.setInteger("bookId", bookId);
				query.setString("property", property);
				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<BookVersion> findBookVersionByBookId(final int bookId, final int firstResult, final int maxResults)
	{
		return (List<BookVersion>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct bv from BookVersion bv where bv.book.bookId=:bookId");
				query.setInteger("bookId", bookId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}
}
